const mongoose = require('mongoose')
const bcrypt = require('bcrypt')

// 用户模式定义
const userSchema = new mongoose.Schema({
  // 基本信息
  email: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    lowercase: true,
    match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, '请提供有效的电子邮件地址']
  },
  password: {
    type: String,
    // 谷歌登录的用户可能没有密码
    required: function() {
      return !this.googleId
    },
    minlength: [6, '密码至少需要6个字符']
  },
  nickname: {
    type: String,
    required: true,
    trim: true
  },
  avatar: {
    type: String,
    default: ''
  },
  bio: {
    type: String,
    default: ''
  },
  
  // 认证相关
  googleId: {
    type: String,
    sparse: true,
    unique: true
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
  isActive: {
    type: Boolean,
    default: true
  },
  
  // 统计数据
  registerDate: {
    type: Date,
    default: Date.now
  },
  lastActive: {
    type: Date,
    default: Date.now
  },
  level: {
    type: Number,
    default: 1
  },
  points: {
    type: Number,
    default: 0
  },
  followingCount: {
    type: Number,
    default: 0
  },
  followerCount: {
    type: Number,
    default: 0
  },
  publicationCount: {
    type: Number,
    default: 0
  },
  
  // 用户设置
  settings: {
    appearance: {
      darkTheme: { type: Boolean, default: false },
      primaryColor: { type: String, default: '#1976D2' },
      fontSize: { type: Number, default: 14 },
      density: { type: String, default: 'comfortable' }
    },
    content: {
      categories: [{ type: Number }],
      languages: [{ type: String }],
      displayMode: { type: String, default: 'grid' }
    },
    privacy: {
      profileVisibility: { type: String, default: 'public' },
      activityTracking: { type: Boolean, default: true },
      showOnlineStatus: { type: Boolean, default: true },
      allowContentSharing: { type: Boolean, default: true }
    },
    notifications: {
      enabled: { type: Boolean, default: true },
      types: [
        {
          type: { type: String },
          enabled: { type: Boolean, default: true }
        }
      ],
      methods: {
        inApp: { type: Boolean, default: true },
        email: { type: Boolean, default: true }
      },
      emailFrequency: { type: String, default: 'daily' }
    }
  }
}, {
  timestamps: true
})

// 创建索引以提高查询性能
userSchema.index({ email: 1 })
userSchema.index({ googleId: 1 }, { sparse: true })
userSchema.index({ role: 1 })
userSchema.index({ isActive: 1 })
userSchema.index({ lastActive: -1 })

// 密码加密中间件
userSchema.pre('save', async function(next) {
  // 只有在密码被修改时才重新加密
  if (!this.isModified('password')) return next()
  
  try {
    // 生成盐值并加密密码
    const salt = await bcrypt.genSalt(10)
    this.password = await bcrypt.hash(this.password, salt)
    next()
  } catch (error) {
    next(error)
  }
})

// 验证密码方法
userSchema.methods.comparePassword = async function(candidatePassword) {
  try {
    return await bcrypt.compare(candidatePassword, this.password)
  } catch (error) {
    throw error
  }
}

// 创建并导出用户模型
const User = mongoose.model('User', userSchema)
module.exports = User